<template>
  <div class="content page-miH page-bgBack">
    <div style="display: flex; justify-content: space-between">
      <selectCompanyGroup :siteIds.sync="siteId" :siteName.sync="siteName" :selectTreeId.sync="selectTreeId" />
      <div>
        <a-button :disabled="!selectedRowKeys.length" @click="barchSetUser">批量设置负责人</a-button>
        <a-button style="margin-left: 12px" type="primary" @click="upLoad">批量导入</a-button>
        <a-button style="margin-left: 12px" type="primary" :disabled="!dataList.length" @click="download">导出</a-button>
      </div>
    </div>
    <div class="head">
      <div style="display: flex">
        <a-month-picker @change="monthChange" v-model="nowDate" :allowClear="false" />
        <a-input-search placeholder="姓名/手机号/身份证号" style="width: 200px; margin-left: 20px" @search="onSearch" />
        <a-popover trigger="click" placement="bottom" style="cursor: pointer" v-model="popoverVisible">
          <div slot="content" style="width: 725px; height: 142px; padding-bottom: 12px">
            <div style="padding: 24px 0; display: flex">
              <div>
                <div style="font-size: 14px; font-weight: 400; color: #636363">负责人姓名</div>
                <a-input v-model="empResponsibleName" placeholder="请输入负责人姓名" style="width: 200px; margin-top: 12px" />
              </div>
              <div style="margin-left: 24px">
                <div style="font-size: 14px; font-weight: 400; color: #636363">回款状态</div>
                <a-select allowClear v-model="planStatus" placeholder="请选择回款状态" style="width: 200px; margin-top: 12px">
                  <a-select-option value="1">未回款</a-select-option>
                  <a-select-option value="2">部分回款</a-select-option>
                  <a-select-option value="3">已回款</a-select-option>
                </a-select>
              </div>
              <div style="margin-left: 24px">
                <div style="font-size: 14px; font-weight: 400; color: #636363">未回款金额筛选</div>
                <a-input-number placeholder="请输入" v-model="surplusAmountMin" :min="0" style="width: 100px; margin-top: 12px" />
                -
                <a-input-number
                  placeholder="请输入"
                  v-model="surplusAmountMax"
                  :min="surplusAmountMin ? surplusAmountMin : 0"
                  style="width: 100px; margin-top: 12px"
                />
              </div>
            </div>

            <div style="display: flex; justify-content: flex-end">
              <a-button @click="popoverVisible = false">取消</a-button
              ><a-button type="primary" style="margin-left: 12px" @click="getRecordInfosList">查询</a-button>
            </div>
          </div>
          <a-button style="margin-left: 12px"><a-icon type="filter" /></a-button>
        </a-popover>
      </div>
      <div>
        <a-button type="link" size="small" style="color: #767885; font-size: 12px" @click="reload">刷新<a-icon type="reload" /></a-button>
        <a-divider type="vertical" />
        <a-popover v-model="headVisible" title trigger="click" placement="bottom" @visibleChange="handleHeadChange">
          <div slot="content" style="width: 600px; height: 320px">
            <div>
              <div>已选择表头</div>
              <div class="overview-tag-wrapper" style="height: 100px; display: flex; overflow-y: auto; flex-direction: column">
                <draggable v-model="tempSelectedHead" filter=".forbid" animation="3000" @start="onStart" @end="onEnd" :move="onMove">
                  <transition-group>
                    <a-tag
                      v-for="(item, index) in tempSelectedHead"
                      :key="index"
                      :closable="item.title !== '姓名'"
                      :color="item.title !== '姓名' ? '#fff' : '#E8E8E8'"
                      :class="item.title !== '姓名' ? 'overview-select-tag' : 'overview-select-tag-name forbid'"
                      @close="deleteSelectedHead($event, index)"
                      >{{ item.title }}</a-tag
                    >
                  </transition-group>
                </draggable>
              </div>
            </div>
            <div>
              <div>可选择表头</div>
              <div style="height: 130px; display: flex; overflow-y: auto; flex-direction: column">
                <div>
                  <a-tag
                    v-for="(item, index) in tempNoSelectedHead"
                    :key="index"
                    class="overview-no-select-tag"
                    @click="addSelectedHead(index)"
                    >{{ item.title }}</a-tag
                  >
                </div>
              </div>
            </div>
            <a-row type="flex" justify="end" style="position: absolute; bottom: 20px; right: 20px">
              <a-button style="margin-right: 12px" @click="handleHeadCancel">取消</a-button>
              <a-button type="primary" @click="handleHeadSearch">查询</a-button>
            </a-row>
          </div>
          <a-button type="link" size="small" style="color: #767885; font-size: 12px">选择表头<a-icon type="menu" /></a-button>
        </a-popover>
      </div>
      <!-- 表头查询 -->
    </div>
    <div class="body">
      <a-table
        :loading="loading"
        :columns="columns"
        :components="components"
        :data-source="dataList"
        :pagination="pagination"
        :customHeaderRow="headerRow"
        @change="handleTableChange"
        :scroll="{ x: 800 }"
        class="xq-draggable-table"
        row-key="id"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      >
        <!-- <template slot="remark" slot-scope="text">{{ text ? text : "--" }}</template> -->

        <!-- <template slot="status" slot-scope="text">
          <span v-if="text === 1" style="display:flex;align-items: center;">
            <div style=" border-radius:50%;height:4px;width:4px;background:#A0A0A0" />
            <span style="margin-left:5px">未回款</span>
          </span>
          <span v-if="text === 2" style="display:flex;align-items: center;">
            <div style=" border-radius:50%;height:4px;width:4px;background:#24CDAA" />
            <span style="margin-left:5px">部分回款</span></span
          >
          <span v-if="text === 3" style="display:flex;align-items: center;">
            <div style=" border-radius:50%;height:4px;width:4px;background:#FFA600" />
            <span style="margin-left:5px">已回款</span></span
          >
        </template> -->
        <!-- <template slot="surplusAmount" slot-scope="text"
          ><span :class="text > 0 ? 'remainClass' : null">{{ text }}</span></template
        > -->
        <!-- <a slot="action" slot-scope="text, record">
          <span class="primary" @click="showAction(record)">
            回款
          </span>
          <a-divider type="vertical" />
          <span class="primary" @click="showRecord(record)">
            回款记录
          </span>
          <a-divider type="vertical" />
          <a-popconfirm
            :title="'确定删除' + record.name + '的回款信息吗？'"
            @confirm="deleteItem(record)"
          >
            <span type="link"> 删除</span>
          </a-popconfirm>
        </a> -->
      </a-table>
      <a-modal v-model="actionVisible" title="新增记录" @ok="handelActionOk">
        <a-form-model ref="ruleForm" :model="actionForm" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-form-model-item ref="name" label="姓名" prop="name">
            <a-input disabled v-model="actionForm.name" placeholder="请输入" />
          </a-form-model-item>
          <a-form-model-item ref="month" label="缴纳月份" prop="month">
            <a-month-picker disabled v-model="actionForm.nowDate" />
          </a-form-model-item>
          <a-form-model-item ref="totalAmount" label="本月应收" prop="totalAmount">
            <a-input disabled v-model="actionForm.totalAmount" placeholder="请输入" />
          </a-form-model-item>
          <a-form-model-item
            ref="wayStatus"
            label="回款途径"
            prop="wayStatus"
            :rules="{
              required: true,
              message: '请选择'
            }"
          >
            <a-select v-model="actionForm.wayStatus" placeholder="请选择回款途径">
              <a-select-option v-for="(item, index) in wayStatusList" :key="index" :value="item.key">{{ item.name }}</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item
            ref="realityAmount"
            :label="actionForm.wayStatus === '5' ? '扣款金额' : '本月实收'"
            prop="realityAmount"
            :rules="{
              required: true,
              message: '请输入'
            }"
          >
            <a-input-number :min="0" v-model="actionForm.realityAmount" placeholder="请输入" />
          </a-form-model-item>
        </a-form-model>
      </a-modal>
      <a-modal v-model="recordVisible" title="回款记录" @ok="handelRecordOk" :width="800">
        <div class="recordTitle">
          <div>姓名：{{ empName }}</div>
          <div>余额：{{ remainAmount }}</div>
        </div>
        <div class="tableBox">
          <a-table size="middle" :pagination="pagination2" @change="handleTableChange2" :columns="recordColumns" :data-source="dataList2">
            <template slot="month" slot-scope="text, record">{{ record.year + "年" + text + "月" }}</template>
            <template slot="wayStatus" slot-scope="text">{{ ["银行", "微信", "支付宝", "其他", "余额扣款"][text - 1] }}</template>
            <template slot="gmtCreate" slot-scope="text">{{ moment(text).format("YYYY-MM-DD HH:mm:ss") }}</template>
          </a-table>
        </div>
      </a-modal>
    </div>
    <a-modal
      :title="isBatch ? '批量设置负责人' : '设置负责人'"
      :visible="setUserVisible"
      @ok="handleUserOk"
      @cancel="setUserVisible = false"
    >
      <div style="display: flex; align-items: center; margin-left: 36px">
        <div style="font-size: 16px; font-weight: 500">计划负责人</div>
        <a-select
          allowClear
          show-search
          option-filter-prop="children"
          :filter-option="filterOption"
          placeholder="请选择管理员"
          style="width: 300px; margin-left: 12px"
          v-model="selectedRecord.empResponsibleId"
          @change="userChange"
        >
          <a-select-option v-for="i in dataSource" :key="i.id">
            {{ i.name }}
          </a-select-option>
        </a-select>
      </div>
    </a-modal>
  </div>
</template>
<script>
import {
  getRecordInfos,
  deleteRecord,
  addRecordRecords,
  getRecordRecords,
  getAllUser,
  settingsResponsible
} from "@/api/shebao/shebaoInfo.js";
import { formatDate, afterTime } from "@/utils/index";
import selectCompanyGroup from "@/components/SelectCompany";
import { mapState } from "vuex";
import moment from "moment";
import DraggableTableCell, { headerRow } from "@/components/DraggableTableCell";
import draggable from "vuedraggable";
import Sortable from "sortablejs";
import ExportMixin from "xqjr-plugin-common/UploadOrExport/exportMixin";
import { renderPoliticalStatus } from "@/views/staff/management/employeeFuncs";
const mixin = new ExportMixin();
const formalType = ["试用", "正式"];
const recordColumns = [
  { title: "月份", dataIndex: "month", key: "month", scopedSlots: { customRender: "month" } },
  { title: "服务费", dataIndex: "serviceCost", key: "serviceCost" },
  { title: "社保费", dataIndex: "socAmount", key: "socAmount" },
  { title: "应收款", dataIndex: "totalAmount", key: "totalAmount" },
  { title: "回款", dataIndex: "realityAmount", key: "realityAmount" },
  {
    title: "回款途径",
    dataIndex: "wayStatus",
    key: "wayStatus",
    scopedSlots: { customRender: "wayStatus" }
  },
  { title: "余额", dataIndex: "amount", key: "amount" },
  {
    title: "操作人",
    dataIndex: "createUserName",
    key: "createUserName",
    scopedSlots: { customRender: "createUserName" }
  },
  {
    title: "操作时间",
    dataIndex: "gmtCreate",
    key: "gmtCreate",
    scopedSlots: { customRender: "gmtCreate" }
  }
];
const initSelectedHead = [
  { title: "姓名", width: 120, dataIndex: "name", key: "name", fixed: "left" },
  { title: "手机号", width: 180, dataIndex: "phone", key: "phone" },
  { title: "身份证号", dataIndex: "idCard", key: "idCard", width: 200 },
  { title: "负责人", dataIndex: "empResponsibleName", key: "empResponsibleName", width: 180 },
  { title: "用工单位", dataIndex: "companyName", key: "companyName", width: 150 },
  { title: "服务费", dataIndex: "serviceCost", key: "serviceCost", width: 120 },
  { title: "社保费", dataIndex: "socAmount", key: "socAmount", width: 120 },
  { title: "应收款", dataIndex: "totalAmount", key: "totalAmount", width: 120 },
  { title: "本月实收", dataIndex: "realityAmount", key: "realityAmount", width: 120 },
  {
    title: "未回款金额",
    dataIndex: "surplusAmount",
    key: "surplusAmount",
    width: 120,
    scopedSlots: { customRender: "surplusAmount" }
  },
  {
    title: "回款状态",
    dataIndex: "status",
    key: "status",
    width: 120,
    scopedSlots: { customRender: "status" }
  },

  { title: "余额", dataIndex: "remainAmount", key: "remainAmount", width: 120 },
  {
    title: "备注",
    dataIndex: "remark",
    key: "remark",
    width: 120
  },
  {
    title: "滞纳金",
    dataIndex: "overdueFine",
    key: "overdueFine",
    width: 120
  }
];
const initNoSelectedHead = [];
const initColumns = [
  { title: "姓名", width: 120, dataIndex: "name", key: "name", fixed: "left" },
  { title: "手机号", width: 180, dataIndex: "phone", key: "phone" },
  { title: "身份证号", dataIndex: "idCard", key: "idCard", width: 200 },
  { title: "负责人", dataIndex: "empResponsibleName", key: "empResponsibleName", width: 180 },

  { title: "用工单位", dataIndex: "companyName", key: "companyName", width: 150 },
  { title: "服务费", dataIndex: "serviceCost", key: "serviceCost", width: 120 },
  { title: "社保费", dataIndex: "socAmount", key: "socAmount", width: 120 },
  { title: "应收款", dataIndex: "totalAmount", key: "totalAmount", width: 120 },
  { title: "本月实收", dataIndex: "realityAmount", key: "realityAmount", width: 120 },
  {
    title: "未回款金额",
    dataIndex: "surplusAmount",
    key: "surplusAmount",
    width: 120,
    scopedSlots: { customRender: "surplusAmount" }
  },
  {
    title: "回款状态",
    dataIndex: "status",
    key: "status",
    width: 120,
    scopedSlots: { customRender: "status" }
  },

  { title: "余额", dataIndex: "remainAmount", key: "remainAmount", width: 120 },
  {
    title: "备注",
    dataIndex: "remark",
    key: "remark",
    width: 120
  },
  {
    title: "滞纳金",
    dataIndex: "overdueFine",
    key: "overdueFine",
    width: 120
  },

  {
    title: "操作",
    dataIndex: "action",
    fixed: "right",
    width: 220,
    scopedSlots: { customRender: "action" },
    align: "center"
  }
];
const columns = [
  { title: "姓名", width: 120, dataIndex: "name", key: "name", fixed: "left" },
  { title: "手机号", width: 180, dataIndex: "phone", key: "phone" },
  { title: "身份证号", dataIndex: "idCard", key: "idCard", width: 200 },
  { title: "负责人", dataIndex: "empResponsibleName", key: "empResponsibleName", width: 180 },
  { title: "用工单位", dataIndex: "companyName", key: "companyName", width: 150 },
  { title: "服务费", dataIndex: "serviceCost", key: "serviceCost", width: 120 },
  { title: "社保费", dataIndex: "socAmount", key: "socAmount", width: 120 },
  { title: "应收款", dataIndex: "totalAmount", key: "totalAmount", width: 120 },
  { title: "本月实收", dataIndex: "realityAmount", key: "realityAmount", width: 120 },
  {
    title: "未回款金额",
    dataIndex: "surplusAmount",
    key: "surplusAmount",
    width: 120,
    scopedSlots: { customRender: "surplusAmount" }
  },
  {
    title: "回款状态",
    dataIndex: "status",
    key: "status",
    width: 120,
    scopedSlots: { customRender: "status" }
  },

  { title: "余额", dataIndex: "remainAmount", key: "remainAmount", width: 120 },
  {
    title: "备注",
    dataIndex: "remark",
    key: "remark",
    width: 120
  },
  {
    title: "滞纳金",
    dataIndex: "overdueFine",
    key: "overdueFine",
    width: 120
  },

  {
    title: "操作",
    dataIndex: "action",
    fixed: "right",
    width: 220,
    scopedSlots: { customRender: "action" },
    align: "center"
  }
];
const draggableTableCell = new DraggableTableCell(columns);
import { mapGetters } from "vuex";
export default {
  mixins: [mixin],
  components: {
    // eslint-disable-next-line vue/no-unused-components
    selectCompanyGroup,
    // eslint-disable-next-line vue/no-unused-components
    draggable
  },
  data() {
    this.components = {
      header: {
        cell: draggableTableCell
      }
    };
    return {
      selectTreeId: "-1",
      siteId: undefined,
      siteName: undefined,
      treeSiteName: undefined,

      nowDate: sessionStorage.getItem("nowDate") ? sessionStorage.getItem("nowDate") : moment(moment().format("YYYY-MM"), "YYYY-MM"),
      columns,
      initColumns,
      selectedRowKeys: [],
      initSelectedHead,
      initNoSelectedHead,
      // 合同状态
      contractsStatus: [
        { id: 0, name: "合同未发起" },
        { id: 1, name: "待员工签署" },
        { id: 2, name: "待公司签署" },
        { id: 3, name: "签署完成" }
      ],
      headVisible: false,
      tempSelectedHead: [],
      tempNoSelectedHead: [],
      setUserVisible: false,
      dataSource: [],
      popoverVisible: false,
      drag: false,
      surplusAmountMax: null,
      surplusAmountMin: null,
      empResponsibleName: null,
      planStatus: undefined,
      recordColumns,
      remainAmount: 0,
      loading: false,
      actionVisible: false,
      recordVisible: false,
      dataList: [],
      dataList2: [],

      labelCol: { span: 8 },
      wrapperCol: { span: 12 },
      actionForm: {},
      empName: "",
      nameOrPhoneOrIdCard: null,
      empId: null,
      formalType,
      selectedRecord: {},
      selectedRowKeys2: [],
      isBatch: false,
      wayStatusList: [
        { key: "1", name: "银行" },
        { key: "2", name: "微信" },
        { key: "3", name: "支付宝" },
        { key: "4", name: "其他" },
        { key: "5", name: "余额扣款" }
      ],
      selectedHead: [],
      pagination2: {
        pageSize: 10,
        total: 0,
        size: "default",
        current: 1,
        showTotal: (total) => `共 ${total} 条`,
        showQuickJumper: true,
        showSizeChanger: true,
        personalPeriod: null,
        editCompanyName: null,
        ticketRecord: null,
        receivableRecord: null
      },
      pagination: {
        pageSize: 10,
        total: 0,
        size: "default",
        current: 1,
        showTotal: (total) => `共 ${total} 条`,
        showQuickJumper: true,
        showSizeChanger: true,
        personalPeriod: null,
        editCompanyName: null,
        ticketRecord: null,
        receivableRecord: null,
        pageSizeOptions: ["10", "20", "50", "100"]
      }
    };
  },
  watch: {
    siteId(newValue) {
      this.getRecordInfosList();
    },
    selectedHead: {
      handler(val) {
        for (let index2 = 0; index2 < this.initColumns.length; index2++) {
          const cols = val.filter((item) => item.title === this.initColumns[index2].title);
          if (cols.length <= 0) {
            // 不显示的列
            if (this.initColumns[index2]["dataIndex"] === "action") {
              // 右边的操作需要显示出来
              this.columns[index2] = Object.assign(this.columns[index2], this.initColumns[index2], {
                customRender: (text, record) => {
                  return (
                    <div>
                      <a style={{ color: "var(--primary)" }} onClick={() => this.showAction(record)}>
                        回款
                      </a>
                      <a-divider type="vertical" />
                      <a style={{ color: "var(--primary)" }} onClick={() => this.showRecord(record)}>
                        回款记录
                      </a>
                      <a-divider type="vertical" />
                      <a-dropdown>
                        <a-menu slot="overlay" onClick={(e) => this.handleMenuClick(e, record)}>
                          <a-menu-item key="1">设置负责人</a-menu-item>
                          <a-menu-item key="2">
                            <div onClick={() => this.deleteItem(record)}>删除</div>
                          </a-menu-item>
                        </a-menu>
                        <a-button type="link">
                          <a-icon type="ellipsis" />
                        </a-button>
                      </a-dropdown>
                    </div>
                  );
                }
              });
            } else {
              // 将不显示的表头宽度设置为0
              this.columns[index2] = Object.assign(this.columns[index2], this.initColumns[index2], {
                width: 0,
                customRender: () => {
                  return null;
                }
              });
            }
          } else {
            // 需要显示的列
            this.columns[index2] = Object.assign(this.columns[index2], this.initColumns[index2], {
              customRender: (text, record) => {
                switch (this.columns[index2]["dataIndex"]) {
                  case "surplusAmount":
                    return <span style="display:flex;align-items: center; color: #fa5051;">{record.surplusAmount}</span>;
                  case "status":
                    return (
                      <span style="display:flex;align-items: center;">
                        <div style=" border-radius:50%;height:4px;width:4px;background:#A0A0A0" />
                        <span style="margin-left:5px">{record.status === 1 ? "未回款" : record.status === 2 ? "部分回款" : "已回款"}</span>
                      </span>
                    );
                  case "joinDate":
                    return <span>{record.joinDate != null ? this.formatDate(record.joinDate) : ""}</span>;
                  case "postType":
                    return <span>{record.postType != null ? this.$store.state.enums.postTypeLst[record.postType - 1] : ""}</span>;
                  case "contractType":
                    return <span>{this.getContractType(record.contractType)}</span>;
                  case "teaMethods":
                    return <span>{this.getTeaMethod(record.teaMethods)}</span>;
                  case "bloodGroup":
                    return <span>{this.getBloodGroup(record.bloodGroup)}</span>;
                  case "regType":
                    return <span>{this.getRegType(record.regType)}</span>;
                  case "politicalStatus":
                    return <span>{renderPoliticalStatus(record.politicalStatus)}</span>;
                  case "birthStatus":
                    return <span>{record.birthStatus != null ? (record.birthStatus === 1 ? "已育" : "未生育") : ""}</span>;
                  case "maritalStatus":
                    return <span>{this.getMaritalStatus(record.maritalStatus)}</span>;
                  case "birthday":
                    return <span>{record.birthday != null ? record.birthday.split(" ")[0] : ""}</span>;
                  case "gender":
                    return <span>{record.gender != null ? (record.gender === 1 ? "男" : "女") : ""}</span>;
                  case "contractStartTime":
                    return <span>{record.contractStartTime != null ? this.formatDate(record.contractStartTime) : ""}</span>;
                  case "contractEndTime":
                    return <span>{record.contractEndTime != null ? this.formatDate(record.contractEndTime) : ""}</span>;
                  case "formalType":
                    return <span>{this.formalType[Number(text - 1)]}</span>;
                  case "contractsStatus":
                    return (
                      <span>{record.contractsStatus != null ? this.getConstractsStatusType(Number(record.contractsStatus)) : ""}</span>
                    );
                  case "isImprove":
                    return (
                      <div class="pointer">
                        {record.isImprove === true && <span class={record.isImprove ? "tc-theme" : "colorC0C0C0"}>•</span>}
                        {record.isImprove === true && <span>已完善</span>}
                        <Popover
                          trigger="click"
                          arrowPointAtCenter
                          content={() => (
                            <div style="width: 200px">
                              <span style="color: red">{record.needComplete}</span>
                              <span>信息未完善</span>
                            </div>
                          )}
                        >
                          {record.isImprove === false && <span class={record.isImprove ? "tc-theme" : "colorC0C0C0"}>•</span>}
                          {record.isImprove === false && <span>未完善</span>}
                        </Popover>
                      </div>
                    );
                  case "verified":
                    return (
                      <div class="pointer">
                        <span class={record.verified ? "tc-theme" : "colorC0C0C0"}>•</span>
                        {record.verified ? "已认证" : "未认证"}
                      </div>
                    );
                  case "tag":
                    if (record.tag) {
                      const arr = record.tag.split(",");
                      return (
                        <Popover placement="topLeft">
                          <template slot="content">
                            <div class="tags-tit">员工标签:</div>
                            <div class="tags-boxs">
                              {arr.map((r) => (
                                <p class="tags-item">{r}</p>
                              ))}
                            </div>
                          </template>
                          <div class="tags">{arr[0]}</div>
                          {arr.length > 1 && <span class="tags-d">...</span>}
                        </Popover>
                      );
                    } else {
                      return <span>{record.tag}</span>;
                    }

                  default:
                    return <span>{text}</span>;
                }
              }
            });
          }
        }
      },
      immediate: true
    }
  },
  created() {
    // 获取缓存的数据
    this.selectTreeId = this.SelectedId;

    this.siteName = this.SelectedName;
    this.siteId = this.SelectedAllIds;

    let temp = localStorage.getItem("stafg");
    if (temp) {
      temp = JSON.parse(temp);
    } else {
      temp = {};
      temp.selectedHead = JSON.parse(JSON.stringify(this.initSelectedHead));
      temp.noSelectedHead = JSON.parse(JSON.stringify(this.initNoSelectedHead));
    }
    this.selectedHead = JSON.parse(JSON.stringify(temp.selectedHead));
    this.noSelectedHead = JSON.parse(JSON.stringify(temp.noSelectedHead));
    this.tempSelectedHead = JSON.parse(JSON.stringify(temp.selectedHead));
    this.tempNoSelectedHead = JSON.parse(JSON.stringify(temp.noSelectedHead));

    for (var i = 0; i < this.selectedHead.length; i++) {
      for (var j = 0; j < this.columns.length; j++) {
        if (this.columns[j].title === this.selectedHead[i].title) {
          this.columns[j] = this.columns.splice(i, 1, this.columns[j])[0];
          this.initColumns[j] = this.initColumns.splice(i, 1, this.initColumns[j])[0];
          break;
        }
      }
    }

    // this.getRecordInfosList();
  },
  computed: {
    ...mapState(["common"]),
    ...mapGetters({
      SelectedId: "site/SelectedId",
      SelectedName: "site/SelectedName",
      SelectedAllIds: "site/SelectedAllIds"
    }),
    cityList() {
      return this.common.cityList;
    },
    areaList() {
      return this.common.areaList;
    }
  },
  mounted() {
    this.initSortable();
    this.getUserRolesList();
  },
  methods: {
    upLoad() {
      this.$router.push({
        path: "socialSecurityPlan/upLoad",
        query: {
          companyIds: !this.siteId || this.siteId === "undefined" || this.siteId === "-1" ? null : this.siteId,

          year: moment(this.nowDate).format("YYYY"),
          month: moment(this.nowDate).format("MM")
        }
      });
    },
    download(i) {
      this.exportData = {
        channelId: this.channelId ? this.channelId : undefined,
        companyIds: !this.siteId || this.siteId === "undefined" || this.siteId === "-1" ? null : this.siteId,

        year: moment(this.nowDate).format("YYYY"),
        month: moment(this.nowDate).format("MM"),
        idList: this.selectedRowKeys.length ? this.selectedRowKeys : undefined,
        nameOrPhoneOrIdCard: this.nameOrPhoneOrIdCard ? this.nameOrPhoneOrIdCard : undefined,
        status: this.planStatus ? this.planStatus : undefined,
        empResponsibleName: this.empResponsibleName ? this.empResponsibleName : undefined,
        surplusAmountMax: this.surplusAmountMax ? this.surplusAmountMax : undefined,
        surplusAmountMin: this.surplusAmountMin ? this.surplusAmountMin : undefined
      };
      this.url = `/hr/api/v1/empSocBackRecordInfos/exportRecordInfo`;
      this.excelName = `${this.siteName}_` + "社保回款计划" + ".xlsx";
      this.postDownload();
    },
    userChange(e) {
      this.empResponsibleId = e;
    },
    onSelectChange(selectedRowKeys, record) {
      var arr = [];
      record.forEach((item) => {
        arr.push(item.empId);
      });
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRowKeys2 = arr;
    },
    getUserRolesList() {
      getAllUser().then((res) => {
        this.dataSource = res.data;
      });
    },
    headerRow,
    initSortable() {
      new Sortable(document.getElementById("sortable_list"), {
        onEnd: this.onDragEnd
      });
      this.selectedHead = JSON.parse(JSON.stringify(this.tempSelectedHead));
      this.noSelectedHead = JSON.parse(JSON.stringify(this.tempNoSelectedHead));
      const temp = {};
      temp.selectedHead = JSON.parse(JSON.stringify(this.selectedHead));
      temp.noSelectedHead = JSON.parse(JSON.stringify(this.noSelectedHead));
      localStorage.setItem("stafg", JSON.stringify(temp));
    },
    onDragEnd(evt) {
      const newIndex = evt.newIndex;
      const oldIndex = evt.oldIndex;
      const columnsTemp = [...this.tempSelectedHead];
      const columnsMap = {};
      const initArr = [];
      for (let i = 0; i < columnsTemp.length; i++) {
        columnsMap[i] = columnsTemp[i];
        initArr.push(i);
      }
      initArr.splice(oldIndex, 1);
      initArr.splice(newIndex, 0, oldIndex);
      const columnsTempNew = initArr.map((idx) => columnsMap[idx]);
      this.tempSelectedHead = columnsTempNew;
      this.components = {
        header: {
          cell: DraggableTableCell(this.tempSelectedHead)
        }
      };
      this.showTable = false;
      this.$nextTick(() => {
        this.showTable = true;
        this.$nextTick(() => {
          this.initSortable();
        });
      });
    },
    getStatus(record) {
      var id = "";
      for (var i = 0; i < this.waiList.length; i++) {
        if (this.waiList[i].empInfoVO.id === record.id) {
          return this.waiList[i].status === 1 ? "未回款" : this.waiList[i].status === 2 ? "部分回款" : "已回款";
        }
      }
    },
    handleUserOk() {
      settingsResponsible({
        empIdList: this.isBatch ? this.selectedRowKeys2 : [this.selectedRecord.empId],
        responsibleId: this.empResponsibleId
      })
        .then((res) => {
          this.setUserVisible = false;
          this.selectedRowKeys = [];
          this.selectedRowKeys2 = [];
          this.$notification["success"]({
            message: "success",
            description: "设置成功"
          });
          this.getRecordInfosList();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getConstractsStatusType(text) {
      return this.contractsStatus[text].name;
    },
    getMaritalStatus(maritalStatus) {
      if (maritalStatus === 1) {
        return "已婚";
      } else if (maritalStatus === 2) {
        return "未婚";
      } else if (maritalStatus === 3) {
        return "离异";
      }
    },
    getRegType(regType) {
      if (regType === 1) {
        return "城镇户口";
      } else if (regType === 2) {
        return "农村户口";
      } else if (regType === 3) {
        return "居民户口";
      }
    },
    getBloodGroup(bloodGroup) {
      if (bloodGroup === 1) {
        return "A";
      } else if (bloodGroup === 2) {
        return "B";
      } else if (bloodGroup === 3) {
        return "AB";
      } else if (bloodGroup === 4) {
        return "O";
      } else if (bloodGroup === 5) {
        return "其它";
      }
    },
    getTeaMethod(teaMethods) {
      if (teaMethods === "1") {
        return "全日制";
      } else if (teaMethods === "2") {
        return "成人教育";
      } else if (teaMethods === "3") {
        return "远程教育";
      } else if (teaMethods === "4") {
        return "自学考试";
      } else if (teaMethods === "5") {
        return "其他非全日制";
      }
    },
    getContractType(contractType) {
      if (contractType === "laborContractLimit") {
        return "固定期限劳动合同";
      } else if (contractType === "laborContractUnlimit") {
        return "无固定期限劳动合同";
      } else if (contractType === "laborContractJobs") {
        return "以完成一定工作任务为期限的劳动合同";
      } else if (contractType === "internAccords") {
        return "实习协议";
      } else if (contractType === "laborContract") {
        return "劳务合同";
      } else if (contractType === "reemployAccords") {
        return "返聘协议";
      } else if (contractType === "laborContractDispatch") {
        return "劳务派遣合同";
      } else if (contractType === "borrowedContract") {
        return "借调合同";
      } else if (contractType === "engagementLetter") {
        return "约定书";
      } else if (contractType === "partTime") {
        return "兼职合同";
      } else if (contractType === "noviciateAgreement") {
        return "见习协议";
      } else if (contractType === "dimissionContract") {
        return "离职合同";
      } else if (contractType === "retireReEmploy") {
        return "退休返聘合同";
      } else if (contractType === "other") {
        return "其它";
      }
    },
    formatDate(text) {
      return formatDate(text);
    },
    // 开始拖拽事件
    onStart() {
      this.drag = true;
    },
    onEnd() {
      this.drag = false;
    },
    // 禁止拖动到id为1的对象
    onMove(e) {
      if (e.relatedContext.element.title === "姓名") return false;
      return true;
    },
    handleHeadChange(visible) {
      if (visible === false) {
        this.tempSelectedHead = JSON.parse(JSON.stringify(this.selectedHead));
        this.tempNoSelectedHead = JSON.parse(JSON.stringify(this.noSelectedHead));
      }
    },
    addSelectedHead(index) {
      const temp = JSON.parse(JSON.stringify(this.tempNoSelectedHead[index]));
      this.tempNoSelectedHead.splice(index, 1);
      this.tempSelectedHead.push(temp);
    },
    deleteSelectedHead(e, index) {
      e.preventDefault();
      const temp = JSON.parse(JSON.stringify(this.tempSelectedHead[index]));
      this.tempSelectedHead.splice(index, 1);
      this.tempNoSelectedHead.push(temp);
    },
    handleHeadSearch() {
      this.selectedHead = JSON.parse(JSON.stringify(this.tempSelectedHead));
      this.noSelectedHead = JSON.parse(JSON.stringify(this.tempNoSelectedHead));
      const temp = {};
      temp.selectedHead = JSON.parse(JSON.stringify(this.selectedHead));
      temp.noSelectedHead = JSON.parse(JSON.stringify(this.noSelectedHead));
      localStorage.setItem("stafg", JSON.stringify(temp));
      this.headVisible = false;
      for (var i = 0; i < this.selectedHead.length; i++) {
        for (var j = 0; j < this.columns.length; j++) {
          if (this.columns[j].title === this.selectedHead[i].title) {
            this.columns[j] = this.columns.splice(i, 1, this.columns[j])[0];
            this.initColumns[j] = this.initColumns.splice(i, 1, this.initColumns[j])[0];
            break;
          }
        }
      }
    },
    handleHeadCancel() {
      this.headVisible = false;
      this.tempSelectedHead = JSON.parse(JSON.stringify(this.selectedHead));
      this.tempNoSelectedHead = JSON.parse(JSON.stringify(this.noSelectedHead));
    },
    // 分页器变化
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.getRecordInfosList();
    },
    handleTableChange2(pagination, filters, sorter) {
      this.pagination2.current = pagination.current;
      this.pagination2.pageSize = pagination.pageSize;
      this.getRecordRecords();
    },
    // 月份选择
    monthChange(e) {
      this.nowDate = e;
      sessionStorage.setItem("nowDate", this.nowDate);
      this.getRecordInfosList();
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
    // 查询信息
    getRecordInfosList() {
      this.loading = true;

      getRecordInfos({
        companyIds: !this.siteId || this.siteId === "undefined" || this.siteId === "-1" ? null : this.siteId,
        "orders[0].property": "status",
        "orders[1].property": "gmtCreate",
        "orders[0].desc": false,
        "orders[1].desc": true,
        year: moment(this.nowDate).format("YYYY"),
        month: moment(this.nowDate).format("MM"),
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize,
        nameOrPhoneOrIdCard: this.nameOrPhoneOrIdCard ? this.nameOrPhoneOrIdCard : undefined,
        status: this.planStatus ? this.planStatus : undefined,
        empResponsibleName: this.empResponsibleName ? this.empResponsibleName : undefined,
        surplusAmountMax: this.surplusAmountMax ? this.surplusAmountMax : undefined,
        surplusAmountMin: this.surplusAmountMin ? this.surplusAmountMin : undefined
      })
        .then((res) => {
          // let state = false;
          this.loading = false;
          this.pagination.total = res.data && res.data.entityCount;
          this.waiList = JSON.parse(JSON.stringify(res.data.entities));
          res.data.entities.forEach((element) => {
            if (element.empInfoVO) {
              for (var key in element.empInfoVO) {
                element[key] = element.empInfoVO[key];
              }
              if (element.bankPlace) {
                const values = this.buildValue(this.getLastAreaId(element.bankPlace));
                const labels = values.map((item) => item.label);
                element.bankPlace = labels.join("-");
              }
            }
          });
          this.dataList = res.data.entities;

          if (res.data.entities.length === 0 && res.data.pageNo > 1) {
            // 当本页非第一页（比第一页大）时，删除最后一条后台会返回当页页码，
            // 但是本页数据为空，table组件会展示为当前页的上一页数据为空，需要加加判断再拉一下上页数据
            this.pagination.current = res.data.pageNo - 1;
            this.pagination.pageSize = 10;
            this.getRecordInfosList();
          }
          // this.dataList.forEach((item, index) => {
          //   if (item.overdueFine !== 0 && item.overdueFine !== null) {
          //     state = true;
          //   }
          // });
          // if (state === true) {
          //   this.columns.splice(this.columns.length - 5, 0, {
          //     title: "滞纳金",
          //     dataIndex: "overdueFine",
          //     key: "overdueFine",
          //     width: 120
          //   });
          // }
          // this.dataList.forEach((item, index) => {
          //   this.dataList[index].remaining =
          //     item.totalAmount - item.realityAmount >= 0
          //       ? item.totalAmount - item.realityAmount
          //       : 0;
          //    });
        })
        .catch((err) => {
          console.log("debug log --> ", err);
          this.loading = false;
        });
    },
    handleMenuClick(e, record) {
      this.getUserRolesList();
      this.selectedRecord = record;
      if (this.selectedRecord.empResponsibleId === null) {
        this.selectedRecord.empResponsibleId = undefined;
      }
      if (e.key === "1") {
        this.setUserVisible = true;
        this.isBatch = false;
      }
    },
    barchSetUser() {
      this.getUserRolesList();
      this.setUserVisible = true;
      this.isBatch = true;
      this.selectedRecord = {};
    },
    buildValue(id, needRecursion = true) {
      id = parseInt(id);
      const index = this.common.areaSourceList.findIndex((item) => item.id === parseInt(id));
      if (index > -1) {
        const item = this.common.areaSourceList[index];
        const val = {
          value: id,
          label: item.name
        };
        if (needRecursion && item.parentId > 0) {
          return this.buildValue(item.parentId).concat([val]);
        } else {
          return [val];
        }
      }
      return [];
    },
    getLastAreaId(values) {
      if (Array.isArray(values)) {
        return values[values.length - 1];
      } else {
        return values.split(",").slice(-1)[0];
      }
    },
    // 搜索
    onSearch(e) {
      this.nameOrPhoneOrIdCard = e;
      this.getRecordInfosList();
    },
    // 删除
    deleteItem(e) {
      // var id = "";
      // for (var i = 0; i < this.waiList.length; i++) {
      //   if (this.waiList[i].empInfoVO.id === e.id) {
      //     id = this.waiList[i].id;
      //     break;
      //   }
      // }
      var that = this;
      this.$confirm({
        title: `确定删除${e.name}的回款信息吗?`,
        onOk() {
          deleteRecord(e.id).then((res) => {
            that.$notification["success"]({
              message: "success",
              description: "删除成功"
            });
            that.getRecordInfosList();
          });
        },
        onCancel() {
          console.log("Cancel");
        }
      });
    },
    reload() {
      this.getRecordInfosList();
      this.$notification["success"]({
        message: "成功",
        description: "刷新成功"
      });
    },
    // 回款记录点击
    showRecord(e) {
      this.empName = e.name;
      this.empId = e.empId;
      this.remainAmount = e.remainAmount;
      this.recordVisible = true;
      this.getRecordRecords();
    },
    getRecordRecords() {
      getRecordRecords({
        year: moment(this.nowDate).format("YYYY"),
        month: moment(this.nowDate).format("MM"),
        pageNo: this.pagination2.current,
        pageSize: this.pagination2.pageSize,
        empId: this.empId
      }).then((res) => {
        this.dataList2 = res.data.entities;
        this.pagination2.total = res.data && res.data.entityCount;
      });
    },
    // 回款记录点击确定
    handelRecordOk() {
      this.recordVisible = false;
    },
    // 点击回款
    showAction(e) {
      this.actionForm = {};
      this.$nextTick(() => {
        this.$refs.ruleForm.clearValidate();
      });
      this.actionForm.name = e.name;
      this.actionForm.phone = e.phone;
      this.actionForm.idCard = e.idCard;
      this.actionForm.totalAmount = e.surplusAmount;
      this.actionForm.empId = e.empId;
      this.actionForm.serviceCost = e.serviceCost;
      this.actionForm.socAmount = e.socAmount;
      this.actionForm.overdueFine = e.overdueFine;
      this.actionForm.nowDate = moment(e.year + "-" + e.month, "YYYY-MM");
      this.actionVisible = true;
    },
    // 新增回款记录(回款点击确定)
    handelActionOk() {
      var dateCopy = this.actionForm.nowDate;
      this.actionForm.year = moment(this.actionForm.nowDate).format("YYYY");
      this.actionForm.month = moment(this.actionForm.nowDate).format("MM");
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.actionForm.nowDate = undefined;
          addRecordRecords(this.actionForm)
            .then((res) => {
              this.$notification["success"]({
                message: "success",
                description: "回款成功"
              });
              this.actionVisible = false;
              this.getRecordInfosList();
            })
            .catch((err) => {
              console.log(err);
              this.actionForm.nowDate = dateCopy;
            });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.overview-no-select-tag {
  background-color: #fff;
  cursor: pointer;
  margin: 5px;
}
.overview-select-tag-name {
  cursor: pointer;
  margin: 5px;
  color: #666666;
}
.overview-select-tag {
  background-color: #fff !important;
  color: var(--primary) !important;
  border: 1px solid var(--primary);
  cursor: pointer;
  margin: 5px;
}
.head {
  display: flex;
  justify-content: space-between;
  margin-top: 24px;
}
.content {
  padding: 24px;
  .body {
    margin-top: 24px;
  }
}
.recordTitle {
  padding: 0 80px;
  display: flex;
  justify-content: space-around;
  color: #3c3d43;
  font-size: 18px;
  font-weight: 500;
}
.tableBox {
  margin-top: 24px;
}
.overview-tag-wrapper {
  ::v-deep .ant-tag {
    .anticon-close {
      color: var(--primary);
    }
  }
}
.remainClass {
  color: #fa5051;
}
</style>
